package com.hkyp.ss.course.web.controller;

import com.hkyp.ss.course.apis.exception.UnacceptableException;
import com.hkyp.ss.course.web.dto.base.ResultBean;
import com.hkyp.ss.course.web.utils.OSSUtil;
import com.hkyp.ss.course.web.utils.UserSessionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;

@Api(description = "上传头像")
@Slf4j
@RestController
@RequestMapping(value = "/a/h/")
public class CommonController {



    /************************************* 上传头像 ********************************************************/
    @ApiOperation(value = "上传图片")
    @RequestMapping(value = "/api/common/upload", method = RequestMethod.POST)
    public ResultBean getUpload(Model model, HttpServletRequest request,
                                @RequestParam(value = "description",required=false) String description,
                                @RequestParam("file") MultipartFile file)throws Exception
    {
        System.out.println(description);
        long userId = UserSessionUtils.getUserId();
        return new ResultBean<>(upload(file,userId));
    }

    public String upload(MultipartFile file, Long userId) {
        //如果文件不为空，写入上传路径
        if(file.isEmpty()){
            throw new UnacceptableException("传入文件为空");
        }
        ;
        String filename = file.getOriginalFilename();
        // 在拦截器里，将JWT里的内容解析成对象，并放到了request里
        /***
         * substring(int beginIndex)
         * 返回一个新的字符串，它是此字符串的一个子字符串。该子字符串从指定索引处的字符开始，直到此字符串末尾。
         *
         * 比如 001.png  以下代码得到  .png
         */
        String suffix=filename.substring(filename.lastIndexOf("."));
        String key = OSSUtil.getImgKey(userId+"",suffix);
        log.info("图片路径(key):"+key);
        OSSUtil.upload(file,key);

        //String link = OSSUtil.getImgUrlPrivate(key);
        String link = OSSUtil.getImgUrl(key);
        log.info("获得访问链接(图片)："+link);

        return link;


    }

}
